//
//  ST_EnjoyCupidViewController.swift
//  btvideo
//
//  Created by Jason on 2021/9/9.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyAttributes
import SwiftyJSON

enum TalkCupidViewType {
    case recommendSomeOne
    case _PrivateConversation
    case matchedConversation
}


enum CupidFactory {
    
    static func currency(for json: JSON,cupidType:TalkCupidViewType) -> UIViewController {
        
        if json["video_url"].url != nil{
            
            let vc = ST_EnjoyCupidViewController()
                    
            vc.over_current_context_alpha = "0.8"
            
            vc.type = cupidType
            
            vc.json = json
            
            vc.overCurrentContext = true
            
            return vc
            
        }else{
        
            let vc = ST_TalkCupidViewController()
                    
            vc.over_current_context_alpha = "0.8"
            
            vc.type = cupidType
            
            vc.json = json
            
            vc.overCurrentContext = true
            
            return vc
            
        }
    }
}


class ST_EnjoyCupidViewController: UIViewController {
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        SCComponets.alert_dispatcher?.nextAlert()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        
        [top_image_view,small_title_label,titleLabel,centerView,online_sub_label,avatar_image_view,nickname_label,user_info_label,content_label,cancel_btn,confirm_btn,free_image_view].forEach({ view.addSubview($0) })
        
        
        centerView.addSubview(cover_image_view)
        centerView.addSubview(playerView)
        centerView.addSubview(gradient_view)
        
        cover_image_view.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        playerView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        gradient_view.snp.makeConstraints { make in
            make.right.left.bottom.equalTo(centerView)
            make.height.equalTo(253)
        }
        
        top_image_view.snp.makeConstraints { (make) in
            make.top.left.equalToSuperview()
            make.right.equalToSuperview().offset(TIANCompatibleValue(value: -44))
            make.height.equalTo(top_image_view.snp.width).dividedBy(1.68)
        }
        
        
        small_title_label.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(44-20+statusBarHeight)
            make.height.equalTo(20)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(74-20+statusBarHeight)
            make.height.equalTo(29)
        }

        
        cancel_btn.snp.makeConstraints { make in
            make.width.equalTo(cancel_btn_image_width)
            make.height.equalTo(cancel_btn_image_width+10+18)
            make.centerX.equalToSuperview().offset(-90/2.0-30)
            make.bottom.equalToSuperview().offset(-38-BTSafeAreaBottom)
        }
        
        confirm_btn.snp.makeConstraints { make in
            make.width.bottom.height.equalTo(cancel_btn)
            make.centerX.equalToSuperview().offset(90/2.0+30)
        }
        
        centerView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.top.equalTo(titleLabel.snp.bottom).offset(20)
            make.bottom.equalTo(cancel_btn.snp.top).offset(-34)
        }
        
        
        free_image_view.snp.makeConstraints { make in
            make.right.equalTo(confirm_btn).offset(21)
            make.top.equalTo(confirm_btn).offset(-14)
            make.height.equalTo(28)
            make.width.equalTo(45)
        }
        
        online_sub_label.snp.makeConstraints { make in
            
            make.right.equalTo(centerView).offset(-15)
            make.top.equalTo(centerView).offset(15)
        }
        
        avatar_image_view.snp.makeConstraints { make in
            make.width.height.equalTo(avatar_image_view_height)
            make.left.equalTo(centerView).offset(15)
            make.bottom.equalTo(centerView).offset(-15)
        }
        
        nickname_label.snp.makeConstraints { make in
            make.left.equalTo(avatar_image_view.snp.right).offset(10)
            make.height.equalTo(20)
            make.top.equalTo(avatar_image_view).offset(5)
        }
        
        user_info_label.snp.makeConstraints { make in
            make.left.equalTo(nickname_label.snp.right).offset(5)
            make.centerY.equalTo(nickname_label)
        }
        
        
        content_label.snp.makeConstraints { make in
            make.left.equalTo(nickname_label)
            make.height.equalTo(20)
            make.top.equalTo(nickname_label.snp.bottom).offset(10)
        }
        
        
        
        bind_data()
    }
    
    fileprivate func bind_data(){
        
        print("丘比特json:",json)
        
        switch type {
        
        case .recommendSomeOne:
            
            let str = json["age"].stringValue + "岁  " + (json["distance"].stringValue.contains("km") ? json["distance"].stringValue : json["distance"].stringValue + "km")
            
            bind(nickname: json["nickname"].stringValue, avatar: json["avatar"].stringValue, coverUrl: json["url"].stringValue, userInfo: str, videoUrl: json["video_url"].url)
            
        case ._PrivateConversation:
            
            let str = (json["distance"].stringValue.contains("km") ? json["distance"].stringValue : json["distance"].stringValue + "km")
            
            bind(nickname: json["nickname_"+targetAccid].stringValue, avatar: json["avatar"].stringValue, coverUrl: json["url"].stringValue, userInfo: str, videoUrl: json["video_url"].url)
            
        case .matchedConversation:
            
            let str = (json["distance"].stringValue.contains("km") ? json["distance"].stringValue : json["distance"].stringValue + "km")
            
            bind(nickname: json["nickname_"+targetAccid].stringValue, avatar: json["avatar_"+targetAccid].stringValue, coverUrl: json["url"].stringValue, userInfo: str, videoUrl: json["video_url"].url)
            
            break
        }
    }

    fileprivate func bind(nickname:String,avatar:String,coverUrl:String,userInfo:String,videoUrl:URL?){
        
        nickname_label.text = nickname
        
        avatar_image_view.pin_setImage(from: avatar.compress_small_image(width: 300).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
        
        cover_image_view.pin_setImage(from: coverUrl.compress_small_image(width: 300*3).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
        
        user_info_label.text = userInfo
        
        if let url = videoUrl{
            playerView.play(url: url)
        }
        
    }
                                                        
    fileprivate func play(url:URL){
            
        pause_video()
        
        playerView.play(url: url)
        
    }
    
    func pause_video(){
      
        playerView.stop()
        
    }
    
    deinit {
        pause_video()
    }
    
    
//     MARK: - properties
    var json = JSON.null
    
    var type = TalkCupidViewType._PrivateConversation
    
    fileprivate lazy var top_image_view:UIImageView = {
    let control = UIImageView.init(image: ST_ImageUtils.imageName("TodayFateCardsTopImage"))
          control.contentMode = .scaleAspectFill
          return control
      }()
    
    fileprivate lazy var small_title_label:UILabel = {
        let l = UILabel()
        l.text = "缘分恋爱来啦！"
        l.textColor = .white
        l.font = .systemFont(ofSize: 14, weight: .medium)
        return l
    }()
    
    fileprivate lazy var titleText = "正在邀请你" + (isVideo ? "视频" : "语音") + "通话！"
    
    fileprivate lazy var titleLabel:UILabel = {
        let l = UILabel()
        l.text = titleText
        l.textColor = .white
        l.font = .systemFont(ofSize: 21, weight: .semibold)
        return l
    }()
    
    fileprivate lazy var centerView:UIView = {
        let l = UIView()
        l.cornerRadius = 16
        return l
    }()
    
    fileprivate lazy var cover_image_view:UIImageView = {
        let v = UIImageView()
        v.contentMode = .scaleAspectFill
        v.cornerRadius = 16
        return v
    }()
    
    fileprivate lazy var playerView:ST_PeculiarityVideoPlayView = {
        let control = ST_PeculiarityVideoPlayView()
        control.isUserInteractionEnabled = false
        control.backgroundColor = .clear
        control.clipsToBounds = true
        control.isMuted = true
        control.loopPlay = true
        control.cornerRadius = 16
        return control
    }()
    
    fileprivate lazy var gradient_view:ST_FWGradientView = {
        let l = ST_FWGradientView()
        l.model = .init(locations: [0,0.5,1], colors: [.clear,#colorLiteral(red: 0.02352941176, green: 0.02352941176, blue: 0.02352941176, alpha: 0.3),#colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.4)], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0, y: 1))
        return l
    }()
    
    
    fileprivate lazy var online_sub_label:ST_OnLineStatusControl = {
        let c = ST_OnLineStatusControl()
        c.bind(text: "在线", isSelected: true)
        return c
    }()
    
    
    fileprivate lazy var avatar_image_view_height = 55/375.0*ScreenWidth
    
    fileprivate lazy var avatar_image_view:UIImageView = {
        
        let control = UIImageView()
        control.contentMode = .scaleAspectFill
        control.cornerRadius = avatar_image_view_height/2.0
        control.borderColor = UIColor.white
        control.borderWidth = 1
        
        return control
    }()
    
    
    fileprivate lazy var content_label:UILabel = {
        let l = UILabel()
        l.text = titleText
        l.textColor = .white
        l.font = .systemFont(ofSize: 14, weight: .medium)
        return l
    }()
    
    fileprivate lazy var nickname_label:UILabel = {
        let l = UILabel()
        l.textColor = .white
        l.font = .systemFont(ofSize: 20, weight: .semibold)
        return l
    }()
    
    fileprivate lazy var user_info_label:UILabel = {
        let l = UILabel()
        l.textColor = .white
        l.font = .systemFont(ofSize: 14, weight: .regular)
        return l
    }()
    
    fileprivate var cancel_btn_image_width = TIANCompatibleValue(value: 80)

    fileprivate lazy var cancel_btn:ST_VerticalButton = {
        let l = ST_VerticalButton()
        l.setImage(ST_ImageUtils.imageName("enjoy_cupid_cancel") ?? UIImage(), for: .normal)
        l.setTitle("继续单身".withAttributes([Attribute.font(.systemFont(ofSize: 15, weight: .regular)),.textColor(#colorLiteral(red: 0.6745098039, green: 0.7058823529, blue: 0.7529411765, alpha: 1))]), for: .normal)
        l.image_view_edges = UIEdgeInsets(top: 0, left: 0, bottom: 10+18, right: 0)
        l.title_bottom_offset = 0
        l.addTarget(self, action: #selector(close_handle), for: .touchUpInside)
        return l
    }()
    
    fileprivate lazy var confirm_btn:ST_VerticalButton = {
        let l = ST_VerticalButton()
        l.setImage(ST_ImageUtils.imageName("enjoy_cupid_confirm") ?? UIImage(), for: .normal)
        l.setTitle("立即接听".withAttributes([Attribute.font(.systemFont(ofSize: 15, weight: .regular)),.textColor(#colorLiteral(red: 0.6745098039, green: 0.7058823529, blue: 0.7529411765, alpha: 1))]), for: .normal)
        l.image_view_edges = UIEdgeInsets(top: 0, left: 0, bottom: 10+18, right: 0)
        l.title_bottom_offset = 0
        l.addTarget(self, action: #selector(confirm_handle), for: .touchUpInside)
        return l
    }()
    
    fileprivate lazy var free_image_view:UIImageView = {
        let v = UIImageView(image: ST_ImageUtils.imageName("enjoy_cupid_free"))
        
        if let attributes = ST_BTUserInfoManager.shared.additional_attributes,attributes.liveTalkFreeNumber > 0 {
            v.alpha = 1
        }else{
            v.alpha = 0
        }
        
        return v
    }()
    

    fileprivate lazy var targetAccid:String = {
        return json["accid"].stringValue
    }()
    
    fileprivate lazy var isVideo:Bool = {
        return json["type"].stringValue == "2"
    }()
}




//MARK: - Event
extension ST_EnjoyCupidViewController{
    
    @objc func confirm_handle(){
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
            return
        }
        
        if ST_MediaChatDispatcher.shared.live_alert_accid_set.contains(json["accid"].stringValue) == false{
            
            self.toast(text: "对方已取消")
            
            return
        }
        
        var eventID = "Chat_Receive"
        
        if isVideo{
            eventID = "Voice" + eventID
        }else{
            eventID = "Video" + eventID
        }
        
        var btnName = "接受通话_男"
        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .female{
            btnName = "接受通话_女"
        }
        
        MobClick.event(eventID, attributes: ["Button_name":btnName])
        
        
//        ST_FateAlertManager.shared.setCurrentAccountMediaTalkFateState(isFinish: true)
        
        goback_previous_controller(animated: true) {
            
            if self.type == .recommendSomeOne{
                
                ST_MediaChatDispatcher.shared.inviteChat(sessionId: self.json["accid"].stringValue, isVideo: self.isVideo,inviteDistract: "upLiveWall")
                
                SCComponets.alert_dispatcher?.finish_recommend_one_stack()
                
            }else{
                
                
                
                ST_MediaChatDispatcher.shared.apply_join_received_invite(json: self.json, isVideo: self.isVideo)
            }
        }
    }
    
    @objc fileprivate func close_handle(){
        
        self.goback_previous_controller(animated: false) {
            
            ST_MediaChatDispatcher.shared.push_cancel_another_invite(accid: self.json["from_accid"].stringValue, isVideo: self.isVideo, text: "对方已拒绝", stopVoice: false)
            
        }
        
        
    }
}
